package com.kim.dingding.signature;

import com.kim.dingding.model.DingdingModel;
import com.kim.dingding.model.vo.SignatureVO;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.codec.binary.Base64;

import javax.crypto.Mac;
import javax.crypto.spec.SecretKeySpec;
import java.net.URLEncoder;

/**
 * @author KimWu
 * @date 2020/6/16 23:35
 * @Description ：
 */

public class Signature {

    public static SignatureVO sign(){
        SignatureVO signatureVO = null;
        try {
            Long timestamp = System.currentTimeMillis();
//            String secret = "SEC86906bd332c8ed7fa4f7de1846a9aefabafdb4b213b328318c3e2b8352ce8460";
            String secret = DingdingModel.secret;
            System.out.println("secret = " + secret);
            String stringToSign = timestamp + "\n" + secret;
            Mac mac = Mac.getInstance("HmacSHA256");
            mac.init(new SecretKeySpec(secret.getBytes("UTF-8"), "HmacSHA256"));
            byte[] signData = mac.doFinal(stringToSign.getBytes("UTF-8"));
            String sign = URLEncoder.encode(new String(Base64.encodeBase64(signData)), "UTF-8");
            signatureVO = new SignatureVO(sign,timestamp);
            return signatureVO;
        }catch (Exception e){
            throw new RuntimeException("钉钉加签失败，请检查secret");
        }
    }
}
